<template>
  <div class="app-container">
    <split-pane :min-percent='10' :default-percent='20' split="vertical">
      <template slot="paneL">
        <el-card class="m-l-5">
          <el-input v-model="filterDeptText" class="m-b-20" placeholder="搜索机构" />
          <el-tree
            ref="deptTree"
            node-key="id"
            :data="treeData"
            :props="treeProps"
            :filter-node-method="filterDeptNode"
            class="filter-tree"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            check-on-click-node
            @node-click="selectDept"
          />
        </el-card>
      </template>

      <template slot="paneR">
        <!-- 搜索区域 -->
        <el-card style="margin:0 0 5px 5px" v-show="showSearch">
          <el-form ref="queryForm" :inline="true" :model="queryData">
            <el-form-item label="登录名称" prop="Q_loginName_S_LK">
              <el-input v-model="queryData.Q_loginName_S_LK" placeholder="登录名称" />
            </el-form-item>
            <el-form-item label="邮箱" prop="Q_email_S_LK">
              <el-input v-model="queryData.Q_email_S_LK" placeholder="邮箱" />
            </el-form-item>
            <el-form-item label="手机号" prop="Q_mobile_S_LK">
              <el-input v-model="queryData.Q_mobile_S_LK" placeholder="手机号" />
            </el-form-item>
            <el-form-item label="用户状态" prop="Q_status_S_EQ">
              <el-select v-model="queryData.Q_status_S_EQ" placeholder="用户状态">
                <el-option label="全部" value="" />
                <el-option
                  v-for="item in optionOfStatus"
                  :key="item.dictCode"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="用户类别" prop="Q_userType_S_EQ">
              <el-select v-model="queryData.Q_userType_S_EQ" class="w-100" placeholder="用户类别">
                <el-option label="全部" value="" />
                <el-option label="系统用户" value="00" />
                <el-option label="注册用户" value="01" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker v-model="queryData.Q_createTime_D_GE" class="width-130" type="date" value-format="yyyy-MM-dd" placeholder="开始时间" />
              -
              <el-date-picker v-model="queryData.Q_createTime_D_LE" class="width-130" type="date" value-format="yyyy-MM-dd" placeholder="结束时间" />
            </el-form-item>
            <el-form-item class="fr p-r-10">
              <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
                搜索
              </el-button>
              <el-button class="filter-item m-l-10" type="info" round icon="el-icon-refresh" @click="handleClear">
                清空
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- table区域 -->
        <el-card class="m-l-5">
          <el-row :gutter="10" class="m-b-5">
            <el-col :span="1.5">
              <el-button v-permission="['system:user:add']" type="primary" size="mini" plain icon="el-icon-plus" @click="handleUserInfo()">
                新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-permission="['system:user:delete']" v-if="selectionData.length > 0" type="danger" size="mini" plain icon="el-icon-delete" @click="handleUserDel()">
                删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-permission="['system:user:export']" type="success" size="mini" plain icon="el-icon-download" @click="handleDownload()">
                下载
              </el-button>
            </el-col>
            <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" :columns="columns" />
          </el-row>
          <el-table
            ref="user_table"
            v-loading="tableLoading"
            :data="tableData"
            element-loading-text="加载中"
            border
            fit
            highlight-current-row
            show-overflow-tooltip
            height="100px"
            v-el-height-adaptive-table="{bottomOffset: 110}"
            @sort-change="sortChange"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="40" />
            <el-table-column v-if="columns[0].visible" align="center" label="登录名" prop="loginName" sortable width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                <span style="cursor: pointer" @click="handleUserInfo(scope.row.userId)">{{ scope.row.loginName }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="columns[1].visible" align="center" label="用户名" prop="userName" sortable width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                <span style="cursor: pointer" @click="handleUserInfo(scope.row.userId)">{{ scope.row.userName }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="columns[2].visible" align="left" label="头像" width="60">
              <template slot-scope="scope">
                <el-avatar shape="circle" fit="fill" :src="getImageSrc(scope.row.avatar)" />
              </template>
            </el-table-column>
            <el-table-column v-if="columns[3].visible" align="center" label="部门" prop="deptName" width="120" show-overflow-tooltip />
            <el-table-column v-if="columns[4].visible" align="center" label="性别" prop="gender" sortable width="90">
              <template slot-scope="scope">
                <el-tag :type="getDictColor('gender', scope.row.gender)" v-text="getDictValue('gender', scope.row.gender)" />
              </template>
            </el-table-column>
            <el-table-column v-if="columns[5].visible" align="center" label="邮箱" prop="email" show-overflow-tooltip />
            <el-table-column v-if="columns[6].visible" align="center" label="手机" prop="mobile" width="200" show-overflow-tooltip />
            <el-table-column v-if="columns[7].visible" align="center" label="状态" prop="status" sortable width="75">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="light" :content="getDictValue('status', scope.row.status)" placement="top">
                  <el-link :type="getDictColor('status', scope.row.status)" :underline="false"><i :class="'el-icon-'+getDictType('status', scope.row.status)"></i></el-link>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column v-if="columns[8].visible" align="center" label="创建时间" sortable width="150" prop="createTime" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.createTime | parseTime('{y}-{m}-{d}') }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-dropdown>
                  <span class="el-dropdown-link">
                    选项<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                      <el-link icon="el-icon-view" @click="handleUserInfo(scope.row.userId)">查看</el-link>
                    </el-dropdown-item>
                    <el-dropdown-item v-permission="['system:user:password']">
                      <el-link type="warning" icon="el-icon-unlock" @click="handleResetPwd(scope.row.userId)">重置密码</el-link>
                    </el-dropdown-item>
                    <el-dropdown-item v-permission="['system:user:delete']">
                      <el-link type="danger" icon="el-icon-delete" @click="handleUserDel(scope.row.userId)">删除</el-link>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
        </el-card>
      </template>
    </split-pane>

    <user-form-dialog v-if="openFormDialog" ref="userForm" @confirmForm="handleFilter" />
  </div>
</template>

<script>
import { userTable, userExport, resetPwd, userDelete } from '@/api/system/user'
import { deptTreeData } from '@/api/system/dept'
import SplitPane from 'vue-splitpane'
import UserFormDialog from './form/dialog'

export default {
  components: {
    SplitPane,
    UserFormDialog
  },
  data() {
    return {
      filterDeptText: '',
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      showSearch: true,
      queryData: {
        Q_deptId_S_EQ: undefined,
        Q_loginName_S_LK: undefined,
        Q_email_S_LK: undefined,
        Q_mobile_S_LK: undefined,
        Q_status_S_EQ: undefined,
        Q_userType_S_EQ: undefined,
        Q_createTime_D_GE: undefined,
        Q_createTime_D_LE: undefined
      },
      optionOfStatus: [],
      optionOfGender: [],
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      columns: [
        { key: 0, label: `登录名`, visible: true },
        { key: 1, label: `用户名`, visible: true },
        { key: 2, label: `头像`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `性别`, visible: true },
        { key: 5, label: `邮箱`, visible: true },
        { key: 6, label: `手机`, visible: true },
        { key: 7, label: `状态`, visible: true },
        { key: 8, label: `创建时间`, visible: true }
      ],
      selectionData: [],
      openFormDialog: false
    }
  },
  watch: {
    filterDeptText(val) {
      this.$refs.deptTree.filter(val)
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 加载下拉菜单
      this.getDictData()
      this.getTreeData()
      this.getTableData()
    },
    filterDeptNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },
    selectDept(data, node) {
      this.queryData.Q_deptId_S_EQ = data.id
      this.handleFilter()
    },
    getImageSrc(value) {
      return this.$api.getImageSrc(value)
    },
    getDictType(property, value) {
      if ('status' === property) {
        return this.$api.getDictElement(this.optionOfStatus, value)[0]
      } else if ('gender' === property) {
        return this.$api.getDictElement(this.optionOfGender, value)[0]
      }
    },
    getDictValue(property, value) {
      if ('status' === property) {
        return this.$api.getDictElement(this.optionOfStatus, value)[1]
      } else if ('gender' === property) {
        return this.$api.getDictElement(this.optionOfGender, value)[1]
      }
    },
    getDictColor(property, value) {
      if ('status' === property) {
        return this.$api.getDictElement(this.optionOfStatus, value)[2]
      } else if ('gender' === property) {
        return this.$api.getDictElement(this.optionOfGender, value)[2]
      }
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.queryData.Q_deptId_S_EQ = undefined
      this.queryData.Q_createTime_D_GE = undefined
      this.queryData.Q_createTime_D_LE = undefined
      this.getTableData()
    },
    getDictData() {
      this.$dictGroup('sys_normal_disable').then(response => {
        this.optionOfStatus = response
      }).catch(e => {})
      this.$dictGroup('sys_user_sex').then(response => {
        this.optionOfGender = response
      }).catch(e => {})
    },
    getTreeData() {
      deptTreeData({
        from: 'vue'
      }).then(response => {
        this.treeData = response
      }).catch(e => {})
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      userTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.user_table.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    handleUserInfo(id) {
      this.openFormDialog = true
      this.$nextTick(() => {
        this.$refs.userForm.init(id, this.queryData.Q_deptId_S_EQ)
      })
    },
    handleDownload() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.$modal.loading('下载中...')
      userExport(query).then(response => {
        window.location.href = this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/download?path=` + encodeURI(response.param) + '&delete=true'
        this.$modal.closeLoading()
      }).catch(e => { this.$modal.closeLoading() })
    },
    handleResetPwd(id) {
      this.$confirm('是否重置该用户密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPwd(id).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    },
    handleUserDel(id) {
      const ids = this.selectionData.map(function(user, index) {
        return user.userId
      }).join(',')

      id = id || ids
      if (!id || id.length === 1) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        userDelete({
          ids: id
        }).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}
</style>
